import 'dart:convert';
import 'package:blurb/common/models/share.dart';
import 'package:blurb/common/values/images.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ShareService {
  static const String _shareListKey = 'share_list';

  // 初始化默认分享
  static Future<void> initDefaultShares() async {
    final prefs = await SharedPreferences.getInstance();
    final shareListStr = prefs.getString(_shareListKey);

    // 如果分享列表为空，创建默认分享
    if (shareListStr == null) {
      final DateTime now = DateTime.now();
      final List<Share> defaultShares = [
        // 用户1的分享
        Share(
          id: 1,
          description: 'today I bought a new sunscreen, the texture is very light and non-sticky, I like it very much!',
          picture: MIP.sunscreen1,
          time: now.subtract(const Duration(days: 2)).toIso8601String(),
          userId: 1,
        ),
        Share(
          id: 2,
          description: 'This sunscreen spray is very convenient to carry, especially suitable for outdoor activities',
          picture: MIP.sunscreen2,
          time: now.subtract(const Duration(days: 1, hours: 12)).toIso8601String(),
          userId: 1,
        ),
        
        // 用户2的分享
        Share(
          id: 3,
          description: 'Tested the waterproof performance of this sunscreen, still effective after 2 hours of swimming! Highly recommended',
          picture: MIP.sunscreen3,
          time: now.subtract(const Duration(days: 3)).toIso8601String(),
          userId: 2,
        ),
        Share(
          id: 4,
          description: 'The summer must-have sunscreen, SPF50, PA++++, completely non-whitening',
          picture: MIP.sunscreen4,
          time: now.subtract(const Duration(hours: 18)).toIso8601String(),
          userId: 2,
        ),
        
        // 用户3的分享
        Share(
          id: 5,
          description: 'Physical sunscreen vs chemical sunscreen, I prefer this physical sunscreen, gentle and non-irritating',
          picture: MIP.sunscreen5,
          time: now.subtract(const Duration(days: 5)).toIso8601String(),
          userId: 3,
        ),
        Share(
          id: 6,
          description: 'Children\'s sunscreen for children, designed for sensitive skin, very safe',
          picture: MIP.sunscreen6,
          time: now.subtract(const Duration(days: 1)).toIso8601String(),
          userId: 3,
        ),
        
        // 用户4的分享
        Share(
          id: 7,
          description: 'Sunscreen also needs to pay attention to ingredients, this one is alcohol-free and fragrance-free, a blessing for sensitive skin',
          picture: MIP.sunscreen7,
          time: now.subtract(const Duration(hours: 6)).toIso8601String(),
          userId: 4,
        ),
        Share(
          id: 8,
          description: 'High-factor sunscreen for beach holidays, water and sweat resistant, safe all day long',
          picture: MIP.sunscreen8,
          time: now.subtract(const Duration(days: 4)).toIso8601String(),
          userId: 4,
        ),
      ];

      // 将分享列表转换为JSON并保存
      final List<Map<String, dynamic>> shareMapList = defaultShares.map((share) => share.toJson()).toList();
      await prefs.setString(_shareListKey, jsonEncode(shareMapList));
    }
  }

  // 获取所有分享
  static Future<List<Share>> getAllShares() async {
    final prefs = await SharedPreferences.getInstance();
    final shareListStr = prefs.getString(_shareListKey);

    if (shareListStr != null) {
      final List<dynamic> shareMapList = jsonDecode(shareListStr);
      return shareMapList.map((shareMap) => Share.fromJson(shareMap)).toList();
    }

    return [];
  }

  // 获取用户的所有分享
  static Future<List<Share>> getUserShares(int userId) async {
    final shares = await getAllShares();
    return shares.where((share) => share.userId == userId).toList();
  }

  // 添加新分享
  static Future<bool> addShare(Share newShare) async {
    final shares = await getAllShares();
    
    // 添加新分享
    shares.add(newShare);
    
    // 保存分享列表
    final prefs = await SharedPreferences.getInstance();
    final List<Map<String, dynamic>> shareMapList = shares.map((share) => share.toJson()).toList();
    await prefs.setString(_shareListKey, jsonEncode(shareMapList));
    
    return true;
  }

  // 更新分享
  static Future<bool> updateShare(Share updatedShare) async {
    final shares = await getAllShares();
    final prefs = await SharedPreferences.getInstance();
    
    // 查找并更新分享
    final index = shares.indexWhere((share) => share.id == updatedShare.id);
    if (index != -1) {
      shares[index] = updatedShare;
      
      // 保存分享列表
      final List<Map<String, dynamic>> shareMapList = shares.map((share) => share.toJson()).toList();
      await prefs.setString(_shareListKey, jsonEncode(shareMapList));
      
      return true;
    }
    
    return false;
  }

  // 删除分享
  static Future<bool> deleteShare(int shareId) async {
    final shares = await getAllShares();
    final prefs = await SharedPreferences.getInstance();
    
    // 查找并删除分享
    final index = shares.indexWhere((share) => share.id == shareId);
    if (index != -1) {
      // 删除分享
      shares.removeAt(index);
      
      // 保存分享列表
      final List<Map<String, dynamic>> shareMapList = shares.map((share) => share.toJson()).toList();
      await prefs.setString(_shareListKey, jsonEncode(shareMapList));
      
      return true;
    }
    
    return false;
  }
} 